package com.wz.jiangsu.handler.MyWebSocketHandler;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wz.jiangsu.bean.MyData;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @program: wz
 * @author: wangzhou
 * @create: 2024-10-27 11:11
 * @description:
 **/
public class MyWebSocketHandler extends TextWebSocketHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收客户端发送的 JSON 数据
        String payload = message.getPayload();
        MyData data = JSONUtil.toBean(payload, MyData.class);

        // 处理 JSON 数据，或将数据发送到后端
        System.out.println("Received data: " + data);
    }

    // 发送 JSON 数据到客户端
    public void sendMessage(WebSocketSession session, MyData data) throws Exception {
        String json = objectMapper.writeValueAsString(data);
        session.sendMessage(new TextMessage(json));
    }

}
